import { router } from '@/router';
import { defineStore } from "pinia"
import { store } from "@/store"
import { getMenuList } from "@/api/menu"
import { ActivedTabItem, MenuState } from "../types/menuState"
import { MenuListRes } from "@/api/menu/types/res"
import { traverseTree } from "@/utils"
import { RouteRecordRaw } from "vue-router"

const defaultMenuState = (): MenuState => ({
    menuList: {
        count: 0,
        list: []
    },
    activedMenuList: JSON.parse(localStorage.getItem('activedMenuList')!) ?? [],
    currentActivedMenuItem: localStorage.getItem('currentActivedMenuItem')! ?? "/home",
    menuCollapsed: false
})


export const MenuStore = defineStore({
    id: "menu-store",
    state: defaultMenuState,
    getters: {
        routeList(): Array<RouteRecordRaw> {
            return this.menuList.list;
        },
    },
    actions: {
        async getMenuList() {
            const menuListRes: MenuListRes = await getMenuList()
            //路由直接属性 eg: route.path
            const routeKeys: Array<string> = ['path', 'name', 'component', 'children', 'meta']

            //需要移除的属性
            const removeItemArray: Array<string> = ['createBy', 'optcreateTimeion2', 'remark', 'updateBy', 'updateTime', 'createTime']

            //将 MenuListRes 类型的数组元素通过动态删除和合并属性转换成 RouteRecordRaw 类型的数组（协变）
            menuListRes.list.forEach((item) => {

                traverseTree(item, (route) => {
                    Object.defineProperty(route, 'meta', { value: {}, configurable: true, enumerable: true, writable: true })

                    for (const key in route) {
                        if (Object.prototype.hasOwnProperty.call(route, key)) {
                            if (removeItemArray.includes(key)) {
                                //删除多余属性
                                delete route[key]
                            } else if (!routeKeys.includes(key)) {
                                //将业务属性拷贝到meta中，然后删除顶层重复属性
                                route.meta[key] = route[key]
                                delete route[key]
                            } else if (key === 'component') {
                                //ES方式动态引入模块
                                // const modules = import.meta.glob('../../views/**/*.vue')
                                const componentPath: string = route[key] ? `../../views/${route[key]}.vue` : ''
                                // route[key] = componentPath ? modules[componentPath] : null

                                //使用dynamicImportVars插件动态引入组件
                                route[key] = componentPath ? () => import(/* @vite-ignore */componentPath) : null
                            }

                        }
                    }

                    //如果是二级菜单则指明重定向路径，方便做面包屑导航
                    if (route.meta.parentId === 0) {
                        route.redirect = `/${route.path}/${route.children[0].path}`
                    }

                })

            })

            this.menuList.count = menuListRes.count
            this.menuList.list = menuListRes.list as Array<RouteRecordRaw>
        },
        addActivedMenuItem(tabItem: ActivedTabItem) {
            //避免插入重复的标签页
            const hasTabItem = this.activedMenuList.find((item) => {
                return item.path == tabItem.path
            })

            !hasTabItem && this.activedMenuList.push(tabItem)
            localStorage.setItem('activedMenuList', JSON.stringify(this.activedMenuList))
        },
        removeActivedMenuItem(tabName: string): string {

            //获得要删除的元素索引
            const index: number = this.activedMenuList.findIndex((item) => {
                return item.path === tabName
            })!

            //返回删除标签的上一个标签路径，实现标签移除时页面关闭,当没有标签页时返回首页
            let lastTabPath = "/home";
            if (index - 1 >= 0) {
                lastTabPath = this.activedMenuList[index - 1].path
            } else if (index === 0 && index + 1 < this.activedMenuList.length) {
                lastTabPath = this.activedMenuList[index + 1].path
            }

            //删除元素
            this.activedMenuList.splice(index, 1)
            localStorage.setItem('activedMenuList', JSON.stringify(this.activedMenuList))

            return lastTabPath
        },
        setCurrentActivedMenuItem(path: string) {
            this.currentActivedMenuItem = path
            localStorage.setItem('currentActivedMenuItem', path)
        }

    },

})


export function useMenuStore() {
    return MenuStore(store)
}
